package com.abel.web.controller;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.abel.domain.Application;
import com.abel.domain.AuthPrincipal;
import com.abel.domain.PersonProfile;
import com.abel.domain.PersonSearchCriteria;
import com.abel.domain.PersonalInformation;
import com.abel.domain.UserRole;
import com.abel.domain.types.UserType;
import com.abel.manager.EducationManager;
import com.abel.manager.PersonProfileManager;
import com.abel.manager.WorkExperienceManager;
import com.abel.repository.exception.NonExistantProfileException;
import com.abel.util.UserSessionLocator;
import com.abel.web.view.DashboardViewBean;

public class DashboardController implements Controller {

	protected final Log logger = LogFactory.getLog(getClass());
	
	private PersonProfileManager personProfileManager;
	
	private EducationManager educationManager;
	
	private WorkExperienceManager workExperienceManager;
	
	
	
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		AuthPrincipal authPrincipal = UserSessionLocator.getUserSession().getAuthPrincipal();
		ModelAndView mav = null;
		DashboardViewBean viewBean = new DashboardViewBean();
		Map<String, Object> modelMap = new HashMap<String, Object>();
		
		//redirecting to the admin dashboard page if the user has admin role
		if (UserSessionLocator.getUserSession().isUserAdmin()) {
			mav = new ModelAndView("admindashboard");
			modelMap.put("dashboardView", viewBean);
			mav.addAllObjects(modelMap);
			return mav;
		}
		
		// for a regular user
		//create the criteria 
		PersonSearchCriteria criteria = new PersonSearchCriteria();
		criteria.setUserId(authPrincipal.getUserId());
		
		//get personalinformation
		PersonalInformation personalInformation = null; 
		try {
			
			PersonProfile personProfile = personProfileManager.getPersonProfile(criteria);
			if (personProfile != null 
					&& personProfile.getPersonalInformation() != null) {
				personalInformation = personProfile.getPersonalInformation();
			}
			
		}
		catch (NonExistantProfileException e) {

			logger.debug("@DashboardController : handleRequest : exception with getting personprofile" + e);
			e.printStackTrace();
			
			//set personalinformation to ensure that viewbean exists for display
			personalInformation = new PersonalInformation();
		}
		catch (Exception e) {
			
			logger.debug("@DashboardController : handleRequest : exception with getting personprofile" + e);
			e.printStackTrace();
			return new ModelAndView("error");
			
		}

		//populate bean if existing application
		viewBean.setSsn(personalInformation.getSsn());
		
		if (personalInformation.getDateOfBirth() != null) {
			viewBean.setDateOfBirth(new SimpleDateFormat("MM/dd/yyyy").format(personalInformation.getDateOfBirth()));
		}
		
		viewBean.setFirstName(personalInformation.getFirstName());
		viewBean.setMi(personalInformation.getMiddleName());
		viewBean.setLastName(personalInformation.getLastName());
		viewBean.setAddress1(personalInformation.getAddressLine1());
		viewBean.setAddress2(personalInformation.getAddressLine2());
		viewBean.setCity(personalInformation.getCity());
		viewBean.setState(personalInformation.getState()); 
		viewBean.setZip(personalInformation.getZip());
		viewBean.setHomePhone(personalInformation.getHomePhone());
		viewBean.setAltPhone(personalInformation.getAlternatePhone());
		viewBean.setWorkPhone(personalInformation.getWorkPhone());
		viewBean.setEmergencyContact(personalInformation.getEmergencyContact());
		viewBean.setEmergencyContactPhone(personalInformation.getEmergencyContactPhone());
		viewBean.setEmergencyContactRelation(personalInformation.getEmergencyContactRelation());
		viewBean.setEmail(authPrincipal.getEmail());

		//setting superadmin user
		List<UserRole> userRoles =  authPrincipal.getRoles();
		
		for (UserRole userRole : userRoles) {
			if (userRole.getRole().equals(UserType.SUPERADMIN.getUserTypeCode())) {
				viewBean.setUserSuperAdmin(true);
				break;
			}
			else if (userRole.getRole().equals(UserType.APPLICANT.name())) {
				viewBean.setUserRegularUser(true);
				break;
			}
		}

		//getting work history to ensure that the threadlocal has all the attributes
		this.workExperienceManager.getWorkExperience(criteria);
		
		//getting education to ensure that the threadlocal has all the attributes
		this.educationManager.getEducationInformation(criteria);

		//disabling links to other parts of the application if personal profile is not set
		Application application = UserSessionLocator.getUserSession().getPerson().getApplication();

		if (application.getApplicationId() > 0) {
			viewBean.setPersonalInfoAvailable(true);
		}
		
		modelMap.put("dashboardView", viewBean);
		
		//if user is admin forward to admindashboard and regular user to dashboard.jsp
//		ModelAndView mav = null;
//		if (UserSessionLocator.getUserSession().isUserAdmin()) {
//			mav = new ModelAndView("admindashboard");
//		}
//		else {
//			mav = new ModelAndView("dashboard");
//		}
		mav = new ModelAndView("dashboard");
		mav.addAllObjects(modelMap);
		return mav;
		
	}
	
	
	

	/**
	 * @param personProfileManager the personProfileManager to set
	 */
	public void setPersonProfileManager(PersonProfileManager personProfileManager) {
		this.personProfileManager = personProfileManager;
	}


	/**http://localhost:8080/AbelWeb/adminregister.xhtm
	 * @param educationManager the educationManager to set
	 */
	public void setEducationManager(EducationManager educationManager) {
		this.educationManager = educationManager;
	}


	/**
	 * @param workExperienceManager the workExperienceManager to set
	 */
	public void setWorkExperienceManager(WorkExperienceManager workExperienceManager) {
		this.workExperienceManager = workExperienceManager;
	}

	
}
